<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #container {
      width: 700px;
      height: 300px;
      border: 2px solid #123;
    }

    #nav {
      width: 100%;
      display: flex;
      justify-content: space-around;
    }

    #nav span {
      width: 25%;
      height: 50px;
      line-height: 50px;
      background: #6c6c6c;
      text-align: center;
      font-size: 1.2em;
      cursor: pointer;
      font-weight: bold;
    }

    #nav span.active {
      background: #fff;
    }

    #content {
      width: 100%;
      height: 100%;
    }

    #content div {
      display: none;
      width: 100%;
      height: 100%;
      text-align: center;
      font-size: 2em;
      line-height: 10em;
      font-weight: bold;
    }

    #content div:first-child {
      display: block;
    }
  </style>
</head>

<body>
  <div id="container">
    <div id="nav">
      <span class="active">国内新闻</span>
      <span>国际新闻</span>
      <span>体育新闻</span>
      <span>娱乐新闻</span>
    </div>
    <div id="content">
      <div>国内新闻</div>
      <div>国际新闻</div>
      <div>体育新闻</div>
      <div>娱乐新闻</div>
    </div>
  </div>
  <script>
    var nav = document.getElementById('nav').getElementsByTagName('span')
    var content = document.getElementById('content').getElementsByTagName('div')
    var container = document.getElementById('container')

    var index = 0

    function handleChange() {
      // 覆盖全局的下标index
      index = this.dataset['index']
      // 清空所有span的默认样式
      for (var i = 0; i < nav.length; i++) {
        nav[i].className = ''
        content[i].style.display = 'none'
      }
      // 在给当前点击的span添加默认样式
      nav[index].className = 'active'
      content[index].style.display = 'block'
    }

    // 给span标签添加自定义属性
    for (var i = 0; i < nav.length; i++) {
      // 增加一个下标属性
      nav[i].dataset['index'] = i
      // 给导航元素绑定事件
      nav[i].onclick = handleChange
    }

    // 封装定时器方法
    function autoplay() {
      // 判断是否有滚动到最后一位
      if (index >= nav.length - 1) {
        index = 0
      } else {
        index++
      }
      // 清空所有span的默认样式
      for (var i = 0; i < nav.length; i++) {
        nav[i].className = ''
        content[i].style.display = 'none'
      }
      // 在给当前点击的span添加默认样式
      nav[index].className = 'active'
      content[index].style.display = 'block'
    }

    var T = setInterval(autoplay, 500)

    // 鼠标移入
    container.onmouseover = function () {
      clearInterval(T)
    }

    container.onmouseout = function () {
      T = setInterval(autoplay, 500)
    }
  </script>
</body>

</html>